// Copyright 2022 a.o.smith ALL Rights Reserved
package com.liuxinlong.modules.assets.service.impl;

import com.liuxinlong.common.SnowFlake;
import com.liuxinlong.constant.ThreadLocalConstants;
import com.liuxinlong.constant.TimeFormatConstants;
import com.liuxinlong.modules.assets.dto.AssetsStatisticsDto;
import com.liuxinlong.modules.assets.dto.OutOrderDto;
import com.liuxinlong.modules.assets.dto.OutOrderExpandDto;
import com.liuxinlong.modules.assets.dto.OutOrderPayDto;
import com.liuxinlong.modules.assets.service.AssetsOrderService;
import com.liuxinlong.modules.dao.AssetsDao;
import com.liuxinlong.modules.dao.AssetsOrderBaseDao;
import com.liuxinlong.modules.dao.AssetsOrderDao;
import com.liuxinlong.modules.dao.AssetsOrderDetailDao;
import com.liuxinlong.modules.dao.AssetsOrderExpandDao;
import com.liuxinlong.modules.dao.AssetsOrderPayDao;
import com.liuxinlong.modules.dao.AssetsStatisticsDao;
import com.liuxinlong.modules.dao.AssetsSupplierDao;
import com.liuxinlong.modules.entity.AssetsOrder;
import com.liuxinlong.modules.entity.AssetsOrderDetail;
import com.liuxinlong.modules.entity.AssetsOrderExpand;
import com.liuxinlong.modules.entity.AssetsOrderPay;
import com.liuxinlong.modules.entity.AssetsStatistics;
import com.liuxinlong.modules.entity.User;
import com.liuxinlong.modules.out.service.OutOrderPayService;
import com.liuxinlong.modules.out.service.OutOrderService;
import com.liuxinlong.utils.DecimalUtils;
import com.liuxinlong.utils.ObjectUtils;
import com.liuxinlong.utils.ThreadlocalUtils;
import com.liuxinlong.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 固资订单管理业务接口层实现
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2024-02-01
 */
@Service
@Slf4j
public class AssetsOrderServiceImpl implements AssetsOrderService {
    @Autowired
    private AssetsDao assetsDao;

    @Autowired
    private OutOrderService outOrderService;

    @Autowired
    private AssetsOrderDao assetsOrderDao;

    @Autowired
    private AssetsStatisticsDao assetsStatisticsDao;

    @Autowired
    private OutOrderPayService outOrderPayService;

    @Autowired
    private AssetsOrderPayDao assetsOrderPayDao;

    @Autowired
    private AssetsOrderBaseDao assetsOrderBaseDao;

    @Autowired
    private AssetsSupplierDao assetsSupplierDao;

    @Autowired
    private AssetsOrderDetailDao assetsOrderDetailDao;

    @Autowired
    private AssetsOrderExpandDao assetsOrderExpandDao;

    @Override
    public List<Map<String, Object>> pageAssetsOrderSyncInfo(Map<String, Object> queryParam) {
        return null;
    }

    @Override
    public void syncAssetsOrderInfo(Map<String, Object> queryParam) {
        List<OutOrderDto> outOrderList = outOrderService.queryOrderList(queryParam);
        List<OutOrderPayDto> outOrderPayList = outOrderPayService.queryOrderPayList(queryParam);
        Map<String, Map<String, String>> assetsMap = assetsDao.getAssetsMap();
        Map<String, Map<String, String>> supplierMap = assetsSupplierDao.getAssetsSupplierMap();
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        Map<String, AssetsOrder> orderAssetsMap = assetsOrderDao.getAssetsOrderMap();
        Map<String, AssetsOrderDetail> orderAssetsDetailMap = assetsOrderDetailDao.getAssetsOrderDetailMap();
        Map<String, BigDecimal> orderMap = new HashMap<>();
        List<AssetsOrder> orderUpdateList = new ArrayList<>();
        List<AssetsOrder> orderAddList = new ArrayList<>();
        List<AssetsOrderDetail> detailUpdateList = new ArrayList<>();
        List<AssetsOrderDetail> detailAddList = new ArrayList<>();
        for (OutOrderDto item : outOrderList) {
            String orderNo = item.getOrderNo().toUpperCase();
            if (StringUtils.isEmpty(orderNo)) {
                log.error(item + " orderNo is empty!");
                continue;
            }
            String assetsNo = StringUtils.isEmpty(item.getAssetsNo()) ? "" : item.getAssetsNo().toUpperCase();
            if (StringUtils.isEmpty(assetsNo)) {
                log.error(item + " assetsNo is empty!");
                continue;
            }
            BigDecimal orderAmount = orderMap.containsKey(orderNo) ? orderMap.get(orderNo) : BigDecimal.ZERO;
            // 订单信息处理
            AssetsOrder orderInfo = orderAssetsMap.containsKey(orderNo) ? orderAssetsMap.get(orderNo) : new AssetsOrder();
            String assetsId = assetsMap.containsKey(assetsNo) ? assetsMap.get(assetsNo).get("id") : "";
            if (!orderMap.containsKey(orderNo)) {
                if (StringUtils.isEmpty(orderInfo.getId())) {
                    orderInfo.setId(SnowFlake.nextIdStr());
                    orderInfo.setAssetsNo(assetsNo);
                    orderInfo.setAssetsId(assetsId);
                    orderInfo.setOrderNo(orderNo);
                    orderInfo.setEffectiveDate(item.getEffectiveDate());
//                    orderInfo.setEffectiveDate(TimeUtils.formatTime(TimeUtils.formatTime(item.getEffectiveDate(), TimeFormatConstants.YYYY_MM_DD), TimeFormatConstants.YYYY_MM_DD));
                    orderInfo.setCloseDate(item.getCloseDate());
                    orderInfo.setSupplierCode(item.getSupplierCode().toUpperCase());
                    orderInfo.setPlant(item.getPlant());
                    String supplierKey = item.getSupplierCode().toUpperCase() + "-" + item.getPlant();
                    orderInfo.setSupplierName(supplierMap.containsKey(supplierKey) ?
                            supplierMap.get(supplierKey).get("supplierName") : "");
                    orderInfo.setBrief(item.getBrief());
                    orderInfo.setBuyer(item.getBuyer());
                    orderInfo.setStatus(StringUtils.isEmpty(item.getStatus()) ? 1 : StringUtils.equals(item.getStatus().toLowerCase(), "c") ? 2 : 0);
                    orderInfo.setRemark(item.getRemark());
                    orderInfo.setCreateTime(currentTime);
                    orderInfo.setCreateUser(ObjectUtils.isEmpty(currentUser) ? "系统" : currentUser.getId());
                    orderAddList.add(orderInfo);
                } else if (orderInfo.getStatus() != (StringUtils.isEmpty(item.getStatus()) ? 1 : StringUtils.equals(item.getStatus().toLowerCase(), "c") ? 2 : 0)) {
                    orderInfo.setStatus(StringUtils.isEmpty(item.getStatus()) ? 1 : StringUtils.equals(item.getStatus().toLowerCase(), "c") ? 2 : 0);
                    orderInfo.setUpdateTime(currentTime);
                    orderInfo.setUpdateUser(ObjectUtils.isEmpty(currentUser) ? "系统" : currentUser.getId());
                    orderUpdateList.add(orderInfo);
                }
            }

            // 订单详情信息处理
            String detailKey = orderNo + "-" + item.getLineNumber();
            AssetsOrderDetail detail = orderAssetsDetailMap.containsKey(detailKey) ? orderAssetsDetailMap.get(detailKey) : new AssetsOrderDetail();
            BigDecimal price = ObjectUtils.isEmpty(item.getPrice()) ? new BigDecimal(0) : item.getPrice();
            BigDecimal amount = DecimalUtils.multiply(price, item.getProductNumber());
            if (StringUtils.isEmpty(detail.getId())) {
                detail.setId(SnowFlake.nextIdStr());
                detail.setOrderId(orderInfo.getId());
                detail.setOrderNo(orderNo);
                detail.setLineNumber(ObjectUtils.isEmpty(item.getLineNumber()) ? 0 : item.getLineNumber().intValue());
                detail.setProductNumber(ObjectUtils.isEmpty(item.getProductNumber()) ? BigDecimal.valueOf(0) : item.getProductNumber());
                detail.setUntaxedAmount(amount);
                detail.setAssetsId(assetsId);
                detail.setRemark(item.getRemark());
                detail.setPlant(item.getDetailPlant());
                detail.setCreateTime(currentTime);
                detail.setCreateUser(ObjectUtils.isEmpty(currentUser) ? "系统" : currentUser.getId());
                detailAddList.add(detail);
            } else if (!BigDecimal.ZERO.equals(DecimalUtils.subtract(amount, detail.getUntaxedAmount()))) {
                detail.setUntaxedAmount(amount);
                detail.setUpdateTime(currentTime);
                detail.setUpdateUser(ObjectUtils.isEmpty(currentUser) ? "系统" : currentUser.getId());
                detailUpdateList.add(detail);
            }
            orderAmount = DecimalUtils.add(orderAmount, amount);
            orderMap.put(orderNo, orderAmount);
            orderAssetsMap.put(orderNo, orderInfo);
            orderAssetsDetailMap.put(detailKey, detail);
        }

        // 处理预付信息
        List<AssetsOrderPay> payList = new ArrayList<>(outOrderPayList.size());
        for (OutOrderPayDto item : outOrderPayList) {
            String orderNo = item.getOrderNo().toUpperCase();
            AssetsOrderPay orderPay = new AssetsOrderPay();
            orderPay.setAssetsId(orderAssetsMap.containsKey(orderNo) ? orderAssetsMap.get(orderNo).getAssetsId() : "");
            orderPay.setId(SnowFlake.nextIdStr());
            orderPay.setOrderNo(orderNo);
            orderPay.setEffectiveDate(item.getTaxDate());
            orderPay.setUntaxedAmount(item.getAmount());
            orderPay.setPlant(item.getPlant());
            orderPay.setCreateUser(ObjectUtils.isEmpty(currentUser) ? "系统" : currentUser.getId());
            orderPay.setCreateTime(currentTime);
            payList.add(orderPay);
        }
        if (!detailAddList.isEmpty()) {
            assetsOrderDetailDao.insertBatch(detailAddList);
        }
        if (!detailUpdateList.isEmpty()) {
            assetsOrderDetailDao.updateBatchById(detailUpdateList);
        }
        if (!orderAddList.isEmpty()) {
            List<AssetsOrder> dataList = new ArrayList<>(orderAddList.size());
            for (AssetsOrder orderInfo : orderAddList) {
                if (orderMap.containsKey(orderInfo.getOrderNo())) {
                    orderInfo.setUntaxedAmount(orderMap.get(orderInfo.getOrderNo()));
                }
                dataList.add(orderInfo);
            }
            assetsOrderDao.insertBatch(dataList);
        }
        // TODO: 2024/2/4  同一订单号，多次增加行数，统计金额
        if (!orderUpdateList.isEmpty()) {
            assetsOrderDao.updateBatchById(orderUpdateList);
        }
        if (!payList.isEmpty()) {
            assetsOrderPayDao.insertBatch(payList);
        }

        List<OutOrderExpandDto> outOrderExpandList = outOrderService.queryOrderExpandList(queryParam);
        List<AssetsOrderExpand> orderExpandList = new ArrayList<>(outOrderExpandList.size());
        for (OutOrderExpandDto dto : outOrderExpandList) {
            AssetsOrderExpand expand = new AssetsOrderExpand();
            expand.setId(SnowFlake.nextIdStr());
            String assetsNo = StringUtils.isEmpty(dto.getAssetsNo()) ? "" : dto.getAssetsNo().toUpperCase();
            if (StringUtils.isEmpty(assetsNo)) {
                log.error(dto + " assetsNo is empty!");
                continue;
            }
            expand.setAssetsNo(assetsNo);
            String assetsId = assetsMap.containsKey(assetsNo) ? assetsMap.get(assetsNo).get("id") : "";
            expand.setAssetsId(assetsId);
            expand.setBrief(dto.getBrief());
            expand.setPlant(dto.getPlant());
            expand.setUntaxedAmount(dto.getAmount());
            expand.setEffectiveDate(dto.getEffectiveDate());
            expand.setCreateUser(currentUser.getId());
            expand.setCreateTime(currentTime);
            orderExpandList.add(expand);
        }
        if (!orderExpandList.isEmpty()) {
            assetsOrderExpandDao.insertBatch(orderExpandList);
        }
    }

    @Override
    public List<Map<String, Object>> pageAssetsOrderInfo(Map<String, Object> queryParam) {
        String currentYear = (String) queryParam.get("currentYear");
        List<AssetsOrder> originalList = assetsOrderDao.pageAssetsOrderInfo(queryParam);
        Map<String, AssetsOrder> orderMap = new HashMap<>();
        Map<String, AssetsOrder> openOrderMap = new HashMap<>();

        Map<String, BigDecimal> orderYearAmountMap = new HashMap<>();
//        Map<String, BigDecimal> orderPayAmountMap = new HashMap<>();
        for (AssetsOrder assetsOrder : originalList) {
            String orderKey = assetsOrder.getOrderNo();
            if (assetsOrder.getStatus() == 2) {
                openOrderMap.put(orderKey, assetsOrder);
            }
            orderMap.put(orderKey, assetsOrder);
        }

        // 获取全部预付
        List<AssetsOrderPay> payList = assetsOrderPayDao.pageAssetsOrderPayInfo(queryParam);
        Map<String, Map<String, List<AssetsOrderPay>>> orderPayMap = new HashMap<>();
        for (AssetsOrderPay pay : payList) {
            String orderNo = pay.getOrderNo().toUpperCase();
            Map<String, List<AssetsOrderPay>> payYearMap = orderPayMap.containsKey(orderNo) ? orderPayMap.get(orderNo) : new HashMap<>();
            String yearKey = pay.getEffectiveDate().substring(0, 4);
            List<AssetsOrderPay> yearPayList = payYearMap.containsKey(yearKey) ? payYearMap.get(yearKey) : new ArrayList<>();
            yearPayList.add(pay);
            payYearMap.put(yearKey, yearPayList);
            orderPayMap.put(orderNo, payYearMap);
        }

        List<String> orderIdList = originalList.stream().map(AssetsOrder::getId).collect(Collectors.toList());
        Map<String, List<AssetsOrderDetail>> assetsDetailMap = new HashMap<>();
        // 获取全部订单详情
        if (!ObjectUtils.isEmpty(orderIdList)) {
            List<AssetsOrderDetail> detailList = assetsOrderDetailDao.getDetailListByOrderId(orderIdList);
            for (AssetsOrderDetail detail : detailList) {
                String orderId = detail.getOrderId();
                List<AssetsOrderDetail> subDetailList = assetsDetailMap.containsKey(orderId) ?
                        assetsDetailMap.get(orderId) : new ArrayList<>();
                subDetailList.add(detail);
                assetsDetailMap.put(orderId, subDetailList);
            }
        }

        List<Map<String, Object>> dataList = new ArrayList<>(originalList.size());
        for (AssetsOrder assetsOrder : originalList) {
            int assetsStartYear = Integer.parseInt(assetsOrder.getEffectiveDate().substring(0, 4));
            List<String> yearList = new ArrayList<>();
            int endYear = Integer.parseInt(StringUtils.isEmpty(assetsOrder.getCloseDate()) ? currentYear : assetsOrder.getCloseDate().substring(0, 4));
            for (int i = assetsStartYear; i <= endYear; i++) {
                yearList.add(String.valueOf(i));
            }
            String orderNo = assetsOrder.getOrderNo();
            Map<String, List<AssetsOrderPay>> payMap = orderPayMap.containsKey(orderNo) ? orderPayMap.get(orderNo) : new HashMap<>();
            // open订单处理
            if (assetsOrder.getStatus() == 2) {
                String costYear = assetsOrder.getCloseDate().substring(0, 4);
                String costYearKey = orderNo + "-" + costYear;
                if (ObjectUtils.isEmpty(payMap)) {
                    // open订单，不存在预付，全部计入close年度
                    BigDecimal amount = orderYearAmountMap.containsKey(costYearKey) ? orderYearAmountMap.get(costYearKey) : new BigDecimal(0);
                    orderYearAmountMap.put(costYearKey, DecimalUtils.add(assetsOrder.getUntaxedAmount(), amount));
                    for (String year : yearList) {
                        if (StringUtils.equals(year, costYear)) {
                            continue;
                        }
                        String yearKey = orderNo + "-" + year;
                        BigDecimal yearAmount = orderYearAmountMap.containsKey(yearKey) ? orderYearAmountMap.get(yearKey) : new BigDecimal(0);
                        orderYearAmountMap.put(yearKey, yearAmount);
                    }
                } else {
                    // open订单，存在预付，预付计入预付年度，除预付外数据计入close年度
                    BigDecimal allPayAmount = BigDecimal.ZERO;
                    for (String year : yearList) {
                        String yearKey = orderNo + "-" + year;
                        BigDecimal yearAmount = orderYearAmountMap.containsKey(yearKey) ? orderYearAmountMap.get(yearKey) : new BigDecimal(0);
                        if (!payMap.containsKey(year)) {
                            orderYearAmountMap.put(yearKey, yearAmount);
                            continue;
                        }
                        List<AssetsOrderPay> orderPayList = payMap.get(year);
                        for (AssetsOrderPay orderPay : orderPayList) {
                            yearAmount = DecimalUtils.add(yearAmount, orderPay.getUntaxedAmount());
                            allPayAmount = DecimalUtils.add(allPayAmount, orderPay.getUntaxedAmount());
                        }
                        orderYearAmountMap.put(yearKey, yearAmount);
                    }
                    BigDecimal yearCostAmount = DecimalUtils.subtract(assetsOrder.getUntaxedAmount(), allPayAmount);
                    BigDecimal yearAmount = orderYearAmountMap.containsKey(costYearKey) ? orderYearAmountMap.get(costYearKey) : BigDecimal.ZERO;
                    yearAmount = DecimalUtils.add(yearAmount, yearCostAmount);
                    orderYearAmountMap.put(costYearKey, yearAmount);
                }
            } else {
                // 未结订单处理
                if (ObjectUtils.isEmpty(payMap)) {
                    // 不存在预付数据
                    for (String year : yearList) {
                        String yearKey = orderNo + "-" + year;
                        BigDecimal yearAmount = orderYearAmountMap.containsKey(yearKey) ? orderYearAmountMap.get(yearKey) : new BigDecimal(0);
                        orderYearAmountMap.put(yearKey, yearAmount);
                    }
//                    continue;
                }
                // 存在预付数据
                for (String year : yearList) {
                    String yearKey = orderNo + "-" + year;
                    BigDecimal yearAmount = orderYearAmountMap.containsKey(yearKey) ? orderYearAmountMap.get(yearKey) : new BigDecimal(0);
                    if (!payMap.containsKey(year)) {
                        orderYearAmountMap.put(yearKey, yearAmount);
                        continue;
                    }
                    List<AssetsOrderPay> orderPayList = payMap.get(year);
                    for (AssetsOrderPay orderPay : orderPayList) {
                        yearAmount = DecimalUtils.add(yearAmount, orderPay.getUntaxedAmount());
                    }
                    orderYearAmountMap.put(yearKey, yearAmount);
                }
            }

            Map<String, Object> item = ObjectUtils.object2Map(assetsOrder);
            BigDecimal lastCostAmount = BigDecimal.ZERO;
            for (String year : yearList) {
                String yearKey = orderNo + "-" + year;
                BigDecimal yearCost = orderYearAmountMap.getOrDefault(yearKey, BigDecimal.ZERO);
                lastCostAmount = DecimalUtils.add(yearCost, lastCostAmount);
            }
            String key = orderNo + "-" + currentYear;
            if (orderYearAmountMap.containsKey(key)) {
                item.put("costAmount", orderYearAmountMap.get(key));
                lastCostAmount = DecimalUtils.subtract(lastCostAmount, orderYearAmountMap.get(key));
            }

            item.put("lastCostAmount", lastCostAmount);
            if (orderPayMap.containsKey(orderNo)) {
                BigDecimal payAmount = BigDecimal.ZERO;
                Map<String, List<AssetsOrderPay>> payInfoMap = orderPayMap.get(orderNo);
                for (List<AssetsOrderPay> orderPayList : payInfoMap.values()) {
                    for (AssetsOrderPay payInfo : orderPayList) {
                        payAmount = DecimalUtils.add(payAmount, payInfo.getUntaxedAmount());
                    }
                }
                item.put("advancePercent", payAmount.multiply(BigDecimal.valueOf(100)).divide(assetsOrder.getUntaxedAmount(), 2, RoundingMode.HALF_UP));
            }
            item.put("detailList", assetsDetailMap.containsKey(assetsOrder.getId()) ? assetsDetailMap.get(assetsOrder.getId()) : "");
            item.put("totalCost", item.containsKey("costAmount") ? DecimalUtils.add((BigDecimal) item.get("costAmount"), lastCostAmount) : lastCostAmount);
            dataList.add(item);
        }

        // 补充订单信息
        List<AssetsOrderExpand> orderExpandList = assetsOrderExpandDao.pageAssetsOrderExpandInfo(queryParam);
        for (AssetsOrderExpand expItem : orderExpandList) {
            String costYear = expItem.getEffectiveDate().substring(0, 4);
            // open订单，不存在预付，全部计入close年度
            Map<String, Object> item = ObjectUtils.object2Map(expItem);
            item.put("status", 2);
            item.put("closeDate",expItem.getEffectiveDate());
            if (StringUtils.equals(currentYear, costYear)) {
                item.put("costAmount", expItem.getUntaxedAmount());
                item.put("lastCostAmount", BigDecimal.ZERO);
            } else {
                item.put("costAmount", BigDecimal.ZERO);
                item.put("lastCostAmount", expItem.getUntaxedAmount());
            }
            dataList.add(item);
        }

        List<Map<String, Object>> sortDataList = dataList.stream().sorted(
                Comparator.comparing((Map<String, Object> h) -> h.containsKey("orderNo") ? (String) h.get("orderNo") : "")).collect(Collectors.toList());
//        List<Map<String, Object>> sortDataList = dataList.stream().sorted(
//                Comparator.comparing((Map<String, Object> h) -> (String) h.get("orderNo")).thenComparing((Map<String, Object> h) -> (Integer) h.get("lineNumber"))).collect(Collectors.toList());
        List<Map<String, Object>> resultList = new ArrayList<>(orderMap.size());
        int sort = (int) queryParam.get("startNum") + 1;
        for (Map<String, Object> item : sortDataList) {
            item.put("sort", sort);
            resultList.add(item);
            sort++;
        }
        return resultList;
    }

    @Override
    public int getAssetsOrderCount(Map<String, Object> queryParam) {
        return assetsOrderDao.getAssetsOrderInfoCount(queryParam);
    }

    @Override
    @Transactional
    public void checkAssetsCost() {
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("startDate", "2019-01-01");
        queryParam.put("endDate", currentTime);
        queryParam.put("startNum", 0);
        queryParam.put("pageSize", 10000);
        List<AssetsOrder> orderList = assetsOrderDao.getAssetsOrderList(queryParam);
//        Map<String, Map<String, String>> orderPayMap = assetsOrderPayDao.getOrderPayMap(queryParam);
        Map<String, Map<String, BigDecimal>> actualCostMap = new HashMap<>();
        Map<String, List<String>> orderAssetsMap = new HashMap<>();
        List<AssetsOrder> openOrderList = orderList.stream().filter(item -> item.getStatus() == 3).collect(Collectors.toList());
        Map<String, BigDecimal> orderOpenMap = new HashMap<>();
        Map<String, Map<String, BigDecimal>> orderPayMap = new HashMap<>();
        for (AssetsOrder order : openOrderList) {
            if (StringUtils.isEmpty(order.getOrderNo())) {
                continue;
            }
//            orderOpenMap.put(order.getOrderNo() + "-" + order.getLineNumber(), order.getUntaxedAmount());
        }
        for (AssetsOrder order : orderList) {
            String assetsNo = order.getAssetsNo();
            if (StringUtils.isEmpty(assetsNo)) {
                continue;
            }
            List<String> orderAssetsList = new ArrayList<>();
            if (orderAssetsMap.containsKey(assetsNo)) {
                orderAssetsList = orderAssetsMap.get(assetsNo);
            }
            if (StringUtils.isEmpty(order.getOrderNo())) {
                continue;
            }
//            String orderKey = order.getOrderNo() + "-" + order.getLineNumber();
            String orderKey = order.getOrderNo();
            if (order.getStatus() == 1) {
                continue;
            } else if (order.getStatus() == 2) {
                String year = order.getEffectiveDate().substring(0, 4);
                if (orderOpenMap.containsKey(orderKey)) {
                    BigDecimal payAmount = new BigDecimal(0);
                    Map<String, BigDecimal> payInfo = new HashMap<>();
                    if (orderPayMap.containsKey(orderKey)) {
                        payInfo = orderPayMap.get(orderKey);
                        if (payInfo.containsKey(year)) {
                            payAmount = DecimalUtils.add(order.getUntaxedAmount(), payInfo.get(year));
                        } else {
                            payAmount = order.getUntaxedAmount();
                        }
                        payInfo.put(year, payAmount);
                    } else {
                        payAmount = order.getUntaxedAmount();
                        payInfo.put(year, payAmount);
                    }
                    orderPayMap.put(orderKey, payInfo);
                    continue;
                }
                Map<String, BigDecimal> actualCost = new HashMap<>();

                if (actualCostMap.containsKey(orderKey)) {
                    actualCost = actualCostMap.get(orderKey);
                    BigDecimal actualYearCost = new BigDecimal(0);
                    if (actualCost.containsKey(year)) {
                        actualYearCost = DecimalUtils.add(actualCost.get(year), order.getUntaxedAmount());
                    } else {
                        actualYearCost = order.getUntaxedAmount();
                    }
                    actualCost.put(year, actualYearCost);
                } else {
                    actualCost.put(year, order.getUntaxedAmount());
                }
                actualCostMap.put(orderKey, actualCost);
            } else if (order.getStatus() == 3) {
                Map<String, BigDecimal> actualCost = new HashMap<>();
                String year = order.getEffectiveDate().substring(0, 4);
                BigDecimal payAmount = new BigDecimal(0);
                if (orderPayMap.containsKey(order.getOrderNo())) {
                    Map<String, BigDecimal> orderPayInfo = orderPayMap.get(orderKey);
                    String payYear = String.valueOf(orderPayInfo.get("effective_date")).substring(0, 4);
                    if (!StringUtils.equals(year, payYear)) {
                        payAmount = new BigDecimal(payYear);
                    }
                }
                if (actualCostMap.containsKey(orderKey)) {
                    actualCost = actualCostMap.get(orderKey);
                    BigDecimal actualYearCost = new BigDecimal(0);
                    if (actualCost.containsKey(year)) {
                        actualYearCost = DecimalUtils.add(actualCost.get(year), order.getUntaxedAmount()).subtract(payAmount);
                    } else {
                        actualYearCost = DecimalUtils.subtract(order.getUntaxedAmount(), payAmount);
                    }
                    actualCost.put(year, actualYearCost);
                } else {
                    actualCost.put(year, DecimalUtils.subtract(order.getUntaxedAmount(), payAmount));
                }
                actualCostMap.put(orderKey, actualCost);
            }
            orderAssetsList.add(orderKey);
            orderAssetsMap.put(assetsNo, orderAssetsList);
        }
        List<AssetsStatisticsDto> statisticsList = assetsStatisticsDao.getStatisticsList(queryParam);
        Map<String, Map<String, String>> assetsMap = assetsDao.getAssetsMap();
        List<AssetsStatistics> updateList = new ArrayList<>();
        for (AssetsStatisticsDto statistics : statisticsList) {
            String assetsNo = statistics.getAssetsNo();
            if (!assetsMap.containsKey(assetsNo)) {
                continue;
            }
//            Map<String,String> assetsInfo = assetsMap.get(statistics.getAssetsId());
//            String assetsNo = assetsInfo.get("assetsNo");
            if (orderAssetsMap.containsKey(assetsNo)) {
                List<String> orderNoList = orderAssetsMap.get(assetsNo);

                BigDecimal actualCost = new BigDecimal(0);
                for (String orderNo : orderNoList) {
                    Map<String, BigDecimal> costInfo = actualCostMap.get(orderNo);
                    if (ObjectUtils.isEmpty(costInfo)) {
                        continue;
                    }
                    actualCost = DecimalUtils.add(actualCost, costInfo.get(statistics.getCurrentYear()));
                }
                if (statistics.getActualAmount().equals(actualCost)) {
                    continue;
                }
                AssetsStatistics newStatistics = new AssetsStatistics();
                newStatistics.setId(statistics.getId());
                newStatistics.setAssetsId(statistics.getAssetsId());
                newStatistics.setSortNum(statistics.getSortNum());
                newStatistics.setCurrentYear(statistics.getCurrentYear());
                newStatistics.setForecastAmount(statistics.getForecastAmount());
                newStatistics.setPlanAmount(statistics.getPlanAmount());
                newStatistics.setCreateTime(statistics.getCreateTime());
                newStatistics.setCreateUser(statistics.getCreateUser());
                newStatistics.setActualAmount(actualCost);
                newStatistics.setUpdateUser(currentUser.getId());
                newStatistics.setUpdateTime(currentTime);
                updateList.add(newStatistics);
            }
        }
        if (!updateList.isEmpty()) {
            assetsStatisticsDao.updateBatchById(updateList);
        }
    }

}
